package com.ktjy.springsecuitydemo.handle;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

/**
 * @return 13141
 * 2025/7/25
 * 14:42
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final String url;

    public MyAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // import org.springframework.security.core.userdetails.User
        User user = (User) authentication.getPrincipal();
        System.out.println("名字：" + user.getUsername());
        // 密码出于安全原因，会显示 null
        System.out.println("密码：" + user.getPassword());
        System.out.println("权限列表：" + user.getAuthorities());
        // 默认登录成功后的处理器中是使用转发形式进行页面跳转
        // 现在自定义的登录成功处理器中使用 response.sendRedirect 重定向进行页面跳转，如此可以跳转到站外链接
        response.sendRedirect(url);
    }
}
